# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

myStartsWith <- function(str, prefix) {
  substring(str, 1, nchar(prefix)) == prefix
}

library(ggplot2)
library(optparse)
library(dplyr)
library(ropls)
library(magrittr)
library(tibble)
library(ggrepel)

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

data <- read.csv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  column_to_rownames("Metabolite")
head(data)
data <- t(data) %>%
  as.data.frame()

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

colorData <- read.csv(opt$sc, header = T, stringsAsFactors = F, comment.char = "") %>%
  select(c("ClassNote", "col"))

uniqueClassNote <- unique(sampleInfo$ClassNote)
for (i in 1:length(uniqueClassNote)) {
  classNote <- uniqueClassNote[i]
  color <- colorData %>%
    filter(ClassNote == classNote) %>%
    .$col %>%
    as.character()
  eachData <- data %>%
    rownames_to_column("SampleID") %>%
    left_join(sampleInfo, by = c("SampleID")) %>%
    filter(ClassNote == classNote) %>%
    column_to_rownames("SampleID")

  x <- eachData %>%
    select(-c("ClassNote"))
  print("==crossValI==")
  crossValI <- min(nrow(x), 7)
  pcaRs <- opls(x, plotL = F, crossvalI = crossValI)
  print("pcaRs")
  print(pcaRs)
  parameterData <- pcaRs@modelDF %>%
    select(c(1:2)) %>%
    set_colnames(c("R2", "Cumulative R2")) %>%
    mutate(pcName = paste0("PC", 1:n())) %>%
    column_to_rownames("pcName") %>%
    t()
  write.csv(parameterData, paste0("PCA_", classNote, "_Parameters.csv"), quote = FALSE)

  print(parameterData)

  pc12 <- pcaRs@scoreMN %>%
    as.data.frame() %>%
    rownames_to_column("Metabolite") %>%
    select(c(1:3)) %>%
    mutate(sample = rep(classNote, nrow(eachData)))

  xBreaks <- seq(-20, 20, by = 10)
  yBreaks <- seq(-15, 15, by = 5)

  fileName <- paste0("PCA_", classNote, "_First2PCs.pdf")

  impoPc1 <- parameterData[1, "PC1"]
  impoPc1 <- round(impoPc1 * 100, 2)
  impoPc2 <- parameterData[1, "PC2"]
  impoPc2 <- round(impoPc2 * 100, 2)

  print(head(pc12))

  p <- ggplot(pc12, mapping = aes(x = p1, y = p2, label = Metabolite)) +
    xlab(paste("PC1(", impoPc1, "%)", sep = "")) +
    ylab(paste("PC2(", impoPc2, "%)", sep = "")) +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(size = 9, hjust = 1, vjust = 0.5),
          axis.text.y = element_text(size = 8.8), legend.position = 'right',
          axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
          legend.text = element_text(size = 8), axis.title.x = element_text(size = 11)
    ) +
    #0 line
    geom_vline(aes(xintercept = 0), colour = "#BEBEBE", linetype = "solid") +
    geom_hline(aes(yintercept = 0), colour = "#BEBEBE", linetype = "solid") +
    #point
    stat_ellipse(colour = "#BEBEBE", size = 0.3, level = 0.95, type = "norm") +
    geom_point(aes(colour = factor(sample)), size = 4, stroke = 0) +
    geom_text_repel(segment.size = 0.2, color = color, size = 2, family = "Times") +
    #lengend
    scale_colour_manual("", values = c(color)) +
    scale_x_continuous(breaks = xBreaks) +
    scale_y_continuous(breaks = yBreaks)
  ggsave(limitsize = FALSE, fileName, p, width = 5, height = 4)
}




